package org.shangrila.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;

import org.shangrila.app.wechat.config.RestTemplateConfiguration;
import org.shangrila.app.wechat.constant.WechatApiUrl;

import org.shangrila.app.wechat.bean.AccessToken;
import org.shangrila.app.wechat.utils.AccessWxUtil;

@Component
public class WeixinAccessTokenTask {
	
	private Logger logger = LoggerFactory.getLogger(WeixinAccessTokenTask.class);
	
	// 第一次延迟1秒执行，当执行完后7100秒再执行
    @Scheduled(initialDelay = 1000, fixedDelay = 7000*1000 )
	public void getWeixinAccessToken() {
    	
		String tokenUrl = WechatApiUrl.GET_TOKEN.replace("ID",AccessWxUtil.appid).replace("SECRECT",AccessWxUtil.secret);
		String mailTokenUr = WechatApiUrl.GET_TOKEN.replace("ID",AccessWxUtil.appid).replace("SECRECT",AccessWxUtil.mailsecret);
		
		try {
			AccessToken accessToken = RestTemplateConfiguration.getRestTemplate().getForObject(tokenUrl, AccessToken.class);
			AccessToken mailAccessToken = RestTemplateConfiguration.getRestTemplate().getForObject(mailTokenUr, AccessToken.class);
			
			if(accessToken!=null && accessToken.getAccess_token()!=null && !accessToken.getAccess_token().isEmpty()) {
				AccessWxUtil.accessToken = accessToken.getAccess_token();
			}
			
			if(mailAccessToken!=null && mailAccessToken.getAccess_token()!=null && !mailAccessToken.getAccess_token().isEmpty()) {
				AccessWxUtil.mailAccessToken = mailAccessToken.getAccess_token();
			}
			logger.error("accessToken errmsg："+mailAccessToken.getErrmsg());
			
		} catch (RestClientException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		
	}
	
}
